package client_tests;

import net.es.lookup.client.RegistrationClient;
import net.es.lookup.common.exception.LSClientException;
import net.es.lookup.common.exception.ParserException;
import net.es.lookup.records.ErrorRecord;
import net.es.lookup.records.Record;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
 * Created with IntelliJ IDEA.
 * User: luke
 * Date: 10/4/13
 * Time: 11:25 AM
 * To change this template use File | Settings | File Templates.
 */
public class MultipleRegistrationThread extends ClientThread {

    private RegistrationClient regClient;

    public MultipleRegistrationThread(String sourceHost, String targetHost,
                                      int port, int tid, int op_interval,
                                      int testRounds) throws LSClientException {

        super(sourceHost, targetHost, port, tid, op_interval, testRounds);
        regClient = new RegistrationClient(sls);
    }

    @Override
    public void executeTestOp() {

        String timestamp = null;
        long testStart = 0;
        long testFinish = 0;

        try {

            DateFormat df = new SimpleDateFormat("MM-dd-HH-mm-ss.SSS");

            testStart = System.currentTimeMillis();
            setOpCode(testStart);
            timestamp = df.format(testStart);

            System.out.println(sourceHost + "-" + tid + "-" + timestamp + ": starting registration");

            Record rec = new Record(TYPE);
            rec.add("op-code", opCode);

            regClient.setRecord(rec);
            rec = regClient.register();
            testFinish = System.currentTimeMillis();

            if (!(rec instanceof ErrorRecord)) {

                int index = rec.getURI().lastIndexOf("/") + 1;
                recordID = rec.getURI().substring(index);
                recordIDs.add(recordID);
            }

            if (rec != null) {

                rx.add(sourceHost + "-" + tid + "-" + timestamp,
                       sls.getConnectionType(),
                       Long.toString(testFinish - testStart) + "ms",
                       Integer.toString(sls.getResponseCode()));
            }

//            System.err.println(testFinish + ": registration finished after " + (testFinish - testStart) / 1000 + " seconds");
        } catch (LSClientException e) {

            rx.add(sourceHost + "-" + tid + "-" + timestamp, sls.getConnectionType(),
                   Long.toString(testFinish - testStart), e.getMessage());
        } catch (ParserException e) {

            rx.add(sourceHost + "-" + tid + "-" + timestamp, sls.getConnectionType(),
                   Long.toString(testFinish - testStart), e.getMessage());
        } finally {

            MultipleRegistrations.decrementPending();
//            clearRecords();
        }
    }
}
